<template>
  <div class="dept-distribution-container">
    <h2>部门资产分布</h2>
    
    <div class="filter-bar">
      <el-select v-model="deptFilter" placeholder="选择部门" @change="handleFilterChange">
        <el-option label="全部部门" value="" />
        <el-option label="技术部" value="技术部" />
        <el-option label="市场部" value="市场部" />
        <el-option label="行政部" value="行政部" />
        <el-option label="财务部" value="财务部" />
        <el-option label="人力资源部" value="人力资源部" />
        <el-option label="运营部" value="运营部" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange"
      />
      <el-button type="primary" @click="refreshData">刷新数据</el-button>
    </div>
    
    <div class="charts-section">
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>部门资产数量分布</span>
          </div>
        </template>
        <div id="deptCountChart" class="chart"></div>
      </el-card>
      
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>部门资产价值分布</span>
          </div>
        </template>
        <div id="deptValueChart" class="chart"></div>
      </el-card>
    </div>
    
    <div class="dept-details">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>部门资产明细</span>
          </div>
        </template>
        <el-table :data="deptDetails" style="width: 100%">
          <el-table-column prop="department" label="部门" />
          <el-table-column prop="assetCount" label="资产数量" />
          <el-table-column prop="totalValue" label="资产总值" :formatter="formatMoney" />
          <el-table-column prop="avgValue" label="平均价值" :formatter="formatMoney" />
          <el-table-column prop="percentage" label="占比" />
          <el-table-column prop="topAssetType" label="主要资产类型" />
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { selectInfoByDeptNameAndDateAPI } from '@/api/asset.js'
import { ElMessage } from 'element-plus'



const deptFilter = ref('') // 部门筛选
const dateRange = ref([]) // 日期筛选范围
const deptDetails = ref([]) // 部门资产详情数据（后端返回）
// 图表实例（存储引用，非响应式）
const countChart = ref(null)
const valueChart = ref(null)


const loadData = async () => {
  try {
    // 处理日期参数（格式化为 YYYY-MM-DD，无日期时传空）
    const startDate = dateRange.value[0]?.toISOString().split('T')[0] || ''
    const endDate = dateRange.value[1]?.toISOString().split('T')[0] || ''

    // 调用后端接口，传入筛选条件
    const res = await selectInfoByDeptNameAndDateAPI({
      deptName: deptFilter.value, // 部门筛选（为空查所有）
      startDate: startDate, // 开始日期
      endDate: endDate // 结束日期
    })

    // 假设后端返回格式（根据实际接口调整字段名）
    if (res.code === 200 && res.data) {
      deptDetails.value = res.data.deptDetails || [] // 部门资产详情数组
      // 数据加载后刷新图表
      initDeptCountChart()
      initDeptValueChart()
    } else {
      deptDetails.value = []
      resetCharts() // 无数据时重置图表
      ElMessage.warning('暂无部门资产分布数据')
    }
  } catch (error) {
    console.error('加载部门资产数据失败：', error)
    deptDetails.value = []
    resetCharts()
    ElMessage.error('数据加载失败，请重试')
  }
}

// ==================== 图表相关 ====================
// 初始化部门资产数量柱状图
const initDeptCountChart = () => {
  const chartDom = document.getElementById('deptCountChart')
  if (!chartDom) return

  // 销毁旧实例，避免内存泄漏
  if (countChart.value) {
    countChart.value.dispose()
  }

  countChart.value = echarts.init(chartDom)

  // 处理图表数据（从 deptDetails 动态提取）
  const xData = deptDetails.value.map(item => item.department)
  const seriesData = deptDetails.value.map(item => item.assetCount)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: '{b} <br/>{a}: {c}台'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%', // 预留更多空间给旋转的x轴标签
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData.length > 0 ? xData : ['暂无数据'],
      axisLabel: {
        rotate: 45,
        interval: 0 // 强制显示所有标签
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: { formatter: '{value}台' }
    },
    series: [
      {
        name: '资产数量',
        type: 'bar',
        data: seriesData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        },
        barWidth: '40%' // 调整柱子宽度，避免拥挤
      }
    ],
    // 无数据提示
    graphic: xData.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  countChart.value.setOption(option)
}

// 初始化部门资产价值柱状图
const initDeptValueChart = () => {
  const chartDom = document.getElementById('deptValueChart')
  if (!chartDom) return

  // 销毁旧实例
  if (valueChart.value) {
    valueChart.value.dispose()
  }

  valueChart.value = echarts.init(chartDom)

  // 处理图表数据（从 deptDetails 动态提取）
  const xData = deptDetails.value.map(item => item.department)
  const seriesData = deptDetails.value.map(item => item.totalValue)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: params => `${params[0].name} <br/>资产价值: ¥${(params[0].value / 10000).toFixed(2)}万`
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xData.length > 0 ? xData : ['暂无数据'],
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        formatter: value => `${(value / 10000).toFixed(1)}万`
      }
    },
    series: [
      {
        name: '资产价值',
        type: 'bar',
        data: seriesData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#fbc2eb' },
            { offset: 0.5, color: '#a18cd1' },
            { offset: 1, color: '#a18cd1' }
          ])
        },
        barWidth: '40%'
      }
    ],
    // 无数据提示
    graphic: xData.length === 0 ? [{
      type: 'text',
      left: 'center',
      top: 'center',
      style: { text: '暂无数据', fontSize: 14, fill: '#999' }
    }] : []
  }

  valueChart.value.setOption(option)
}

// 重置图表为无数据状态
const resetCharts = () => {
  initDeptCountChart()
  initDeptValueChart()
}

// 图表自适应窗口大小
const handleResize = () => {
  countChart.value && countChart.value.resize()
  valueChart.value && valueChart.value.resize()
}

// ==================== 工具与交互方法 ====================
// 金额格式化（表格专用）
const formatMoney = (cellValue) => {
  return '¥' + cellValue.toLocaleString('zh-CN')
}

// 日期筛选变化
const handleDateChange = () => {
  refreshData()
}

// 部门筛选变化
const handleFilterChange = () => {
  refreshData()
}

// 刷新数据（筛选条件变化时调用）
const refreshData = () => {
  console.log('刷新数据：', {
    deptFilter: deptFilter.value,
    dateRange: dateRange.value
  })
  loadData() // 重新调用接口加载数据
}

// ==================== 生命周期 ====================
// 组件挂载时加载初始数据
onMounted(() => {
  loadData()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表+移除事件
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  countChart.value && countChart.value.dispose()
  valueChart.value && valueChart.value.dispose()
})

// 暴露金额格式化方法给模板
defineExpose({
  formatMoney
})
</script>

<style scoped>
.dept-distribution-container {
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 320px;
}

.dept-details {
  margin-top: 30px;
}
</style>